﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Century.Web.Security.Attributes
using GKFX.Common.Business.BOL.Common;
using Telerik.Web.Mvc;
using GKFX.Common.UI.MVC;

namespace Century.Web.MVC.AdminArea
{
    [Authorization(Group = "", Name = "Administration")]
    public class UserSiteManagementController : CenturyAdminBaseController
    {
        //
        // GET: /UserSiteManagement/
        UserBSO userBSO = new UserBSO();
        CountrySiteBSO countrySiteBSO = new CountrySiteBSO();

        public ActionResult Index()
        {
            return View();
        }

        [GridAction]
        public ActionResult GetUserList()
        {
            var model = new GridModel
            {
                Data = userBSO.GetAll().Select(e => new { e.Id, e.UserName, e.FirstName, e.LastName, e.IsAdministrator })
            };
            return View(model);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [GridAction]
        public ActionResult EditUser(int id)
        {
            GKFX.Models.Common.User user = userBSO.Find(c => c.Id == id);
            TryUpdateModel(user);
            userBSO.Update(user);
            var model = new GridModel
            {
                Data = userBSO.GetAll().Select(e => new { e.Id, e.UserName, e.FirstName, e.LastName, e.IsAdministrator })
            };
            return View(model);
        }

        [GridAction]
        public ActionResult GetCountriesForUser(int userId)
        {
            IEnumerable<GKFX.Models.Common.CountrySite> countrySites = countrySiteBSO.GetAll();
            IEnumerable<GKFX.Models.Common.CountrySite> userCountries = userBSO.GetCountriesForUser(userId);
            var confDetails = countrySites.Select(c =>
                new
                {
                    c.Id,
                    c.Name,
                    c.Path,
                    UserHasThisCountrySite = userCountries.Any(a => a.Id == c.Id)
                });
            return View(new GridModel(confDetails));
        }

        public string ChangeUserCountries(int userId, int countrySiteId, bool userHasThisCountry)
        {
            GKFX.Models.Common.User user = userBSO.Find(c => c.Id == userId, "CountrySites");
            GKFX.Models.Common.CountrySite countrySite = userBSO.FindCountrySite(countrySiteId);
            if (userHasThisCountry)
            {
                user.CountrySites.Add(countrySite);
            }
            else
            {
                user.CountrySites.Remove(countrySite);
            }
            userBSO.Update(user);
            return string.Empty;
        }

    }
}
